// src/router/index.js (Vue 3 版本)
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../view/Hello.vue';
import About from '../view/About.vue';
import Next from '../view/Next.vue';
import Login from '../view/Login.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/about',
    name: 'About',
    component: About,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/next',
    name: 'Next',
    component: Next,
    meta: {
      requiresAuth: true
    }
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局导航守卫，检查登录状态
router.beforeEach((to, from, next) => {
  // 检查路由是否需要授权
  if (to.meta.requiresAuth) {
    // 从localStorage获取登录状态
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    
    if (isLoggedIn) {
      // 已登录，允许访问
      next();
    } else {
      // 未登录，重定向到登录页
      next({ name: 'Login' });
    }
  } else {
    // 不需要授权的页面，直接放行
    next();
  }
});

export default router;